#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>

#define BUFF_SIZE 1024

class TCP_CLIENT
{
public:
    TCP_CLIENT(std::string ip, uint16_t port)
        : _server_port(port), _server_ip(ip), _sockfd(-1) {}

    void client_init()
    {
        // 创建套接字
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd < 0) std::cout<< "create socket error" << std::endl;

        //客户端不需要显示的绑定端口
        //只需要向服务端发起请求连接
    }

    void client_start()
    {
        struct sockaddr_in _to_server;
        memset(&_to_server, 0, sizeof(_to_server));
        _to_server.sin_family = AF_INET;
        _to_server.sin_port = htons(_server_port);
        _to_server.sin_addr.s_addr = inet_addr(_server_ip.c_str());
        socklen_t len = sizeof _to_server;

        int check = connect(_sockfd, (struct sockaddr*)&_to_server, len);
        if (check == -1) std::cout << "connect server error" << std::endl;
        else std::cout<< "connect server success" << std::endl;

        while(true)
        {
            std::string to_message;
            std::cout << "please enter: ";
            std::cin >> to_message;

            write(_sockfd, to_message.c_str(), to_message.size());
            char recv_buff[BUFF_SIZE] = {0};
            ssize_t size = read(_sockfd, recv_buff, sizeof recv_buff -1);
            if (size > 0)
            {
                recv_buff[size] = '\0';
                std::cout << recv_buff << std::endl;
            }
            else break;
        }
    }

private:
    std::string _server_ip;
    uint16_t _server_port;
    int _sockfd;
};